package com.xiaour.spring.boot.page;

import io.grpc.stub.StreamObserver;
import net.devh.boot.grpc.server.service.GrpcService;

import java.util.ArrayList;
import java.util.List;

@GrpcService

public class PaginationServiceImpl extends PaginationServiceGrpc.PaginationServiceImplBase {
    @Override
    public void getItems(PageProto.PageRequest request, StreamObserver<PageProto.PageResponse> responseObserver) {
        int pageNumber = request.getPageNumber();
        int pageSize = request.getPageSize();

        List<PageProto.Item> items = new ArrayList<>();
        for (int i = 1; i <= 100; i++) {
            items.add(PageProto.Item.newBuilder().setId(i).setName("Item " + i).build());
        }

        int totalItems = items.size();
        int totalPages = (int) Math.ceil((double) totalItems / pageSize);

        int start = (pageNumber - 1) * pageSize;
        int end = Math.min(start + pageSize, totalItems);
        List<PageProto.Item> paginatedItems = items.subList(start, end);

        PageProto.PageResponse response = PageProto.PageResponse.newBuilder()
                .setCurrentPage(pageNumber)      // 当前页码
                .setTotalPages(totalPages)        // 总页数
                .setTotalItems(totalItems)        // 总项数
                .setPageSize(pageSize)            // 每页数量
                .addAllItems(paginatedItems)      // 当前页数据集合
                .build();

        responseObserver.onNext(response);
        responseObserver.onCompleted();
    }

}